//
//  WmcEditFieldContentView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/9.
//

import UIKit
import YPBedrock

// MARK: - [WmcEditFieldContentView]

class WmcEditFieldContentView: WmcBaseView {
    lazy var titleLabel: UILabel = {
        let label = UILabel.YP.Create(text: "标题",
                                      font: 16.yp.uiFont(weight: .medium),
                                      color: UIColor.wmc_grayH2_323233,
                                      alignment: .left)
        return label
    }()

    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.textColor = .wmc_grayH2_323233
        textField.font = 14.wmc_font
        textField.layer.cornerRadius = 4
        textField.layer.masksToBounds = true
        textField.backgroundColor = .wmc_grayH19_F5F5F5
        textField.leftView = .init(frame: CGRect(origin: .zero, size: Wmc_standardEdge.left.yp.cgSize))
        textField.leftViewMode = .always
        textField.delegate = self
        return textField
    }()

    lazy var countLabel: UILabel = {
        let label = UILabel.YP.Create(font: 16.wmc_font,
                                      color: UIColor.wmc_grayH8_8A8A99,
                                      alignment: .left)
        return label
    }()

    lazy var contentLabel: UILabel = {
        let label = UILabel.YP.Create(text: "内容",
                                      font: titleLabel.font,
                                      color: titleLabel.textColor,
                                      alignment: titleLabel.textAlignment)
        return label
    }()

    lazy var textView: WmcTextView = {
        let textView = WmcTextView()
        textView.font = textField.font
        return textView
    }()

    lazy var completeBtn: UIButton = {
        let btn = UIButton.Wmc_themeColorBtn(color: .wmc_mainTheme, title: "确认")
        btn.titleLabel?.font = 14.wmc_font
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        return btn
    }()

    lazy var maskLayer: CAShapeLayer = {
        let maskLayer = CAShapeLayer()
        return maskLayer
    }()

    lazy var shadowView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = bottomCornerRadius
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 1, height: 3)
        view.layer.shadowRadius = bottomCornerRadius
        view.layer.shadowOpacity = 0.1
        return view
    }()

    lazy var stackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [
            titleLabel,
            textField,
            contentLabel,
            textView,
        ])
        stackView.spacing = 8
        stackView.axis = .vertical
        stackView.alignment = .fill
        stackView.distribution = .fill
        return stackView
    }()

    /// 标题最大限制
    var textFieldMaxCount = 8

    /// 底部圆角半径
    var bottomCornerRadius: CGFloat = 8

    /// 索引
    var indexPath: IndexPath?

    /// 模型
    var model: WmcWatermarkOptionModel?

    /// 确定回调
    var submitBlock: YPBlock.TwoParam<IndexPath, WmcWatermarkOptionModel>?

    override func makeUI() {
        backgroundColor = .clear

        let animationTopHeight: CGFloat = 20

        addSubview(shadowView)
        shadowView.snp.makeConstraints { make in
            make.top.equalTo(-animationTopHeight)
            make.left.right.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }

        addSubview(completeBtn)
        completeBtn.snp.makeConstraints { make in
            make.width.equalTo(65.wmc_autoHor)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.height.equalTo(35.wmc_autoVer)
            make.bottom.equalTo(-Wmc_standardEdge.bottom)
        }

        titleLabel.yp.layoutHeightEqual(22)
        textField.yp.layoutHeightEqual(45)
        contentLabel.yp.layoutHeightEqual(22)

        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(Wmc_standardEdge.top + animationTopHeight)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.bottom.equalTo(completeBtn.snp.top).offset(-12)
        }

        textField.addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.right.equalTo(-Wmc_standardEdge.right)
        }
    }
    
    override func bindViewModel() {
        
        completeBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self,
                  let model = weakSelf.model,
                  let indexPath = weakSelf.indexPath else { return }
            // 修改值
            model.isOpen = true
            model.title = weakSelf.textField.text ?? model.title
            model.content = weakSelf.textView.text ?? model.content
            // 回调
            weakSelf.submitBlock?(indexPath, model)
            weakSelf.dismiss()
        }
    }

    func configModel(_ model: WmcWatermarkOptionModel) {
        self.model = model
        // 设置显示
        titleLabel.isHidden = !model.enableEditTitle
        textField.isHidden = !model.enableEditTitle

        contentLabel.isHidden = !model.enableEditContent
        textView.isHidden = !model.enableEditContent

        // 设置内容
        textField.text = model.title

        // 设置限制
        if model.fieldType == .isolation { // 疫情天数
            textView.maxCount = 2
        } else {
            textView.maxCount = 100
        }

        if model.contentText == WmcWatermarkOptionModel.defaultContentText ||
            model.contentText == WmcWatermarkOptionModel.defaultRecordContentText ||
            model.contentText == WmcWatermarkOptionModel.defaultIsolationContentText
        { // 占位
            textView.text = ""
        } else {
            textView.text = model.contentText
        }

        textField.returnKeyType = .done
        textView.textView.returnKeyType = .default
        textView.textView.keyboardType = .default
        switch model.fieldType {
        case .title:
            textView.textView.returnKeyType = .done
//        case .text:
//        case .record:
        case .isolation:
            textView.textView.keyboardType = .numberPad
        default: break
        }

        // 空跑一下
        textFieldDidChangeSelection(textField)
    }

    func setFirstResponder() {
        textView.textView.becomeFirstResponder()
    }
}

// MARK: - UITextFieldDelegate

extension WmcEditFieldContentView: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        guard var text = textField.text else { return }

        if let lang = textField.textInputMode?.primaryLanguage,
           lang == "zh-Hans",
           let selectRange = textField.markedTextRange
        {
            let position = textField.position(from: selectRange.start, offset: 0)
            if position == nil {
                if text.count > textFieldMaxCount {
                    text = text.yp.keepPrefix(count: textFieldMaxCount)
                    textField.text = text
                }
            }
        } else {
            if text.count > textFieldMaxCount {
                text = text.yp.keepPrefix(count: textFieldMaxCount)
                textField.text = text
            }
        }
        
        let textCount = textField.text?.count ?? 0
        countLabel.text = "\(textCount)/\(textFieldMaxCount)"

        textView.textView.keyboardType = .default
        switch model?.fieldType {
        case .title:
            if let title = textField.text {
                textView.placeholderLabel.text = "请输入\(title)"
            } else {
                textView.placeholderLabel.text = "请输入标题"
            }
        case .text:
            if let title = textField.text {
                textView.placeholderLabel.text = "请输入\(title)"
            } else {
                textView.placeholderLabel.text = "请输入内容"
            }
        case .record:
            textView.placeholderLabel.text = WmcWatermarkOptionModel.defaultRecordContentText
        case .isolation:
            textView.placeholderLabel.text = WmcWatermarkOptionModel.defaultIsolationContentText
            textView.textView.keyboardType = .numberPad
        default: break
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField.returnKeyType {
        case .done:
            if string == "\n" {
                textField.resignFirstResponder()
                return false
            }
        default: break
        }
        return true
    }
}

// MARK: - WmcAlertViewProtocol

extension WmcEditFieldContentView: WmcAlertViewProtocol {}
